package com.foreknow.controller;

import com.foreknow.bean.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 转发与重向的区别
 * 1. 转发 req.getRequestDispatcher("get").forward(req,resp); 相当于发送一次请求
 * 2. 重定向 resp.sendRedirect("http://www.163.com");
 * 3. 转发只能转发站内资源而重定向可以定向到任意资源(站内、站外)
 * 4. 转发会使用第一次发送请求的资源地址 http://localhost:8085/MavenWebBasic/add
 *    重定向直接定向到目标资源  http://localhost:8085/MavenWebBasic/get
 */
public class GetMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器向客户端响应的内容的类型
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端发送请求的字符编码集
        req.setCharacterEncoding("utf-8");
        //通过getWriter方法获取PrintWriter输出流对象，主要用于在网页上输出结果
        PrintWriter out = resp.getWriter();
        //调用Service的方法查询所有留言信息
        GuestbookService service = new GuestbookServiceImpl();
        List<Object> list = service.queryAll();
        //需要创建几行几列的表格？2行7列
        out.println("<table border='1'>");
        out.println("<tr>");
        out.println("<td>id</td>");
        out.println("<td>name</td>");
        out.println("<td>phone</td>");
        out.println("<td>email</td>");
        out.println("<td>title</td>");
        out.println("<td>content</td>");
        out.println("<td>createdtime</td>");
        out.println("</tr>");
        for(int i = 0;i<list.size();i++) {
            Guestbook gb = (Guestbook) list.get(i);
            out.println("<tr>");
            out.println("<td>"+gb.getId()+"</td>");
            out.println("<td>"+gb.getName()+"</td>");
            out.println("<td>"+gb.getPhone()+"</td>");
            out.println("<td>"+gb.getEmail()+"</td>");
            out.println("<td>"+gb.getTitle()+"</td>");
            out.println("<td>"+gb.getContent()+"</td>");
            out.println("<td>"+gb.getCreatedtime()+"</td>");
            out.println("</tr>");
        }
        out.println("</table>");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
